<template>
	<view class="chart-page">
		<!-- 头部筛选 -->
		<view class="filter-container">
			<picker mode="date" fields="month" @change="handleMonthChange">
				<view class="filter-item">
					<uni-icons type="calendar" size="18" color="#7fbc8d"></uni-icons>
					<text>{{ currentMonth }}</text>
				</view>
			</picker>

		</view>

		<!-- 图表容器 -->
		<view class="chart-container">
			<canvas canvas-id="costChart" id="costChart" type="2d" class="charts" @touchstart="touchStart"
				@touchmove="touchMove" @touchend="touchEnd"></canvas>
		</view>

		<!-- 统计摘要 -->
		<view class="stats-summary">
			<view class="stat-item">
				<text class="stat-value">¥{{ totalCost }}</text>
				<text class="stat-label">总花费</text>
			</view>
			<view class="stat-item">
				<text class="stat-value">{{ totalVolume }}L</text>
				<text class="stat-label">总油量</text>
			</view>
			<view class="stat-item">
				<text class="stat-value">{{ avgConsumption }}L/100km</text>
				<text class="stat-label">平均油耗</text>
			</view>
		</view>

		<!-- 详细数据 -->
		<view class="data-table">
			<view class="table-header">
				<text class="header-item">日期</text>
				<text class="header-item">油量(L)</text>
				<text class="header-item">金额(¥)</text>
				<text class="header-item">里程(km)</text>
			</view>

			<view class="table-row" v-for="(item, index) in records" :key="index">
				<text class="row-item">{{ item.refuelDate }}</text>
				<text class="row-item">{{ item.oilVolume }}</text>
				<text class="row-item">{{ item.amount }}</text>
				<text class="row-item">{{ item.mileage }}</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		computed
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import uCharts from '@/utils/u-charts.min.js'

	import {
		getCurrentInstance
	} from 'vue'
	import dayjs from 'dayjs'
	const {
		proxy
	} = getCurrentInstance()

	// 数据状态
	const selectedMonth = dayjs(new Date()).format('YYYY-MM')
	const currentMonth = ref(selectedMonth)
	const records = ref([{
			refuelDate: selectedMonth+'-01',
			oilVolume: 42.5,
			amount: 320,
			mileage: 12300
		},
	])

	// 计算属性
	const totalCost = computed(() => {
		return records.value.reduce((sum, item) => sum + item.amount, 0)
	})

	const totalVolume = computed(() => {
		return records.value.reduce((sum, item) => sum + item.oilVolume, 0)
	})

	const avgConsumption = computed(() => {
		const totalKm = records.value[records.value.length - 1].mileage - records.value[0].mileage
		return (totalVolume.value / totalKm * 100).toFixed(2)
	})

	// 方法
	const formatDate = (date) => {
		return date.split('-').slice(1).join('-')
	}


	const handleMonthChange = (e) => {
		currentMonth.value = e.detail.value
		updateChartData()
	}


	const updateChartData = () => {
		// 这里应该调用API获取数据
		console.log('加载月份数据:', currentMonth.value)
		loadData()
	}
	
	const categoriesData = ref([1,2])
	const seriesData = ref([1,2])
	

	const chartData = {
		categories: categoriesData,
		series: [{
			name: '加油量',
			data: seriesData,
			color: '#7fbc8d',
			type: 'column',
			barWidth: 20,
			seriesGap: 0.2, // 添加默认间距
			pointShape: 'rect' // 指定形状
		}]
	}


	const initChart = () => {
		console.log("加载chart")
		return new Promise((resolve) => {
			// 创建查询
			const query = uni.createSelectorQuery()
			query.select('#costChart')
				.fields({
					node: true,
					size: true
				})
				.exec((res) => {
					if (!res[0]?.node) {
						return setTimeout(() => initChart().then(resolve), 2000)
					}

					const canvas = res[0].node
					const ctx = canvas.getContext('2d')
					const {
						windowWidth,
						pixelRatio
					} = uni.getSystemInfoSync()
					// 设置canvas实际尺寸
					canvas.width = res[0].width * pixelRatio
					canvas.height = res[0].height * pixelRatio
					ctx.scale(1, 1)
					// 初始化图表
					const config = {
						canvasId: 'costChart',
						type: 'column',
						context: ctx,
						width: res[0].width,
						height: res[0].height,
						categories: categoriesData.value,
						series: chartData.series.map(series => ({
							...series,
							seriesGap: series.seriesGap || 0.2,
							data: seriesData.value,
							type: series.type || 'column',
							pointShape: series.pointShape || 'rect'
						})),
						extra: {
							column: {
								type: 'stack', // 或 'stack' 堆叠模式
								width: 10,
								seriesGap: 0.2,
								categoryGap: 0.5
							}
						}
					}
					chartData.value = new uCharts(config)
					resolve()
				})
		})
	}

	const loadData = async () => {
		try {
			const params = {
				page: 1,
				pageSize: 100,
				month: currentMonth.value,
			}
			const res = await proxy.$api.getStatistics(params)
			console.log(res)
			if (res.code === 200) {
				records.value = res.data.list
				categoriesData.value = res.data.categories
				seriesData.value = res.data.seriesData
	
				initChart().catch(err => {
					console.error('图表初始化失败:', err)
				})
			}
		} catch (error) {
			console.error('加载数据失败:', error)
		} finally {
			
		}
	}


	onMounted(() => {
		setTimeout(() => {
			loadData()
		}, 300)
	});
</script>

<style scoped>
	.chart-container {
		position: relative;
		width: 100%;
		height: 400px !important;
		/* 固定高度 */
		padding: 20rpx;
		box-sizing: border-box;
	}

	.charts {
		width: 100%;
		height: 500rpx;
		display: block;
		/* 关键样式 */

		position: absolute !important;
		left: 0 !important;
		top: 0 !important;
		width: 100% !important;
		height: 100% !important;
	}

	.chart-page {
		padding: 20rpx;
		background-color: #f8f8f8;
		min-height: 100vh;
	}

	.filter-container {
		display: flex;
		justify-content: space-between;
		margin-bottom: 30rpx;
	}

	.filter-item {
		background-color: white;
		border-radius: 40rpx;
		padding: 16rpx 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.filter-item text {
		margin-left: 10rpx;
		font-size: 28rpx;
	}

	.chart-container {
		background-color: white;
		border-radius: 16rpx;
		padding: 20rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.charts {
		width: 100%;
		height: 300px;
	}

	.stats-summary {
		display: flex;
		justify-content: space-between;
		margin-bottom: 30rpx;
	}

	.stat-item {
		width: 32%;
		background-color: white;
		border-radius: 16rpx;
		padding: 30rpx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.stat-value {
		font-size: 36rpx;
		font-weight: bold;
		color: #7fbc8d;
		margin-bottom: 8rpx;
	}

	.stat-label {
		font-size: 26rpx;
		color: #999;
	}

	.data-table {
		background-color: white;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.table-header {
		display: flex;
		background-color: #f5f5f5;
		padding: 20rpx 0;
	}

	.header-item {
		flex: 1;
		text-align: center;
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
	}

	.table-row {
		display: flex;
		padding: 25rpx 0;
		border-bottom: 1rpx solid #eee;
	}

	.table-row:last-child {
		border-bottom: none;
	}

	.row-item {
		flex: 1;
		text-align: center;
		font-size: 28rpx;
		color: #666;
	}
</style>